package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.LabinfoItemData;
import com.ruoyi.system.domain.LabinfoSampleData;
import com.ruoyi.system.mapper.LabinfoItemDataMapper;
import com.ruoyi.system.mapper.LabinfoSampleDataMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ILabinfoItemDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class LabinfoItemDataServiceImpl implements ILabinfoItemDataService
{
    private static final Logger log = LoggerFactory.getLogger(LabinfoItemDataServiceImpl.class);
    @Autowired
    private LabinfoItemDataMapper labinfoItemDataMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 查询【项目】
     *
     * @param id 【项目】主键
     * @return 【项目】
     */
    @Override
    public LabinfoItemData selectLabinfoItemDataById(Long id)
    {
        return labinfoItemDataMapper.selectLabinfoItemDataById(id);
    }

    /**
     * 查询【项目】列表
     *
     * @param labinfoItemData 【项目】
     * @return 【项目】
     */
    @Override
    public List<LabinfoItemData> selectLabinfoItemDataList(LabinfoItemData labinfoItemData)
    {
        return labinfoItemDataMapper.selectLabinfoItemDataList(labinfoItemData);
    }

    /**
     * 新增【项目】
     *
     * @param labinfoItemData 【项目】
     * @return 结果
     */
    @Override
    public int insertLabinfoItemData(LabinfoItemData labinfoItemData)
    {
        labinfoItemData.setCreateTime(DateUtils.getNowDate());
        return labinfoItemDataMapper.insertLabinfoItemData(labinfoItemData);
    }

    /**
     * 修改【项目】
     *
     * @param labinfoItemData 【项目】
     * @return 结果
     */
    @Override
    public int updateLabinfoItemData(LabinfoItemData labinfoItemData)
    {
        labinfoItemData.setUpdateTime(DateUtils.getNowDate());
        return labinfoItemDataMapper.updateLabinfoItemData(labinfoItemData);
    }

    /**
     * 批量删除【项目】
     *
     * @param ids 需要删除的【项目】主键
     * @return 结果
     */
    @Override
    public int deleteLabinfoItemDataByIds(Long[] ids)
    {
        return labinfoItemDataMapper.deleteLabinfoItemDataByIds(ids);
    }

    /**
     * 删除【项目】信息
     *
     * @param id 【项目】主键
     * @return 结果
     */
    @Override
    public int deleteLabinfoItemDataById(Long id)
    {
        return labinfoItemDataMapper.deleteLabinfoItemDataById(id);
    }

    @Override
    public List<LabinfoItemData> getItemByReceiveDate(Map map) {

        String sjdwName = map.get("sjdwName")== null?"": map.get("sjdwName").toString();
        String patientPhone = map.get("patientPhone")== null?"": map.get("patientPhone").toString();
        String receiveSampleDate = map.get("receiveSampleDate")== null?"": map.get("receiveSampleDate").toString();
        String sjys = "";
        LoginUser loginUser = SecurityUtils.getLoginUser();//获取当前登录信息
        SysUser sysUser = loginUser.getUser();
        if(sysUser != null){
            String isRegister = sysUser.getIsRegister();
            if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){
                sjys = sysUser.getNickName();
            }
        }
        return labinfoItemDataMapper.getItemByReceiveDate(sjdwName,patientPhone,receiveSampleDate,sjys);
    }

    @Override
    public List<Map> getItemListBySampleDecWay1(LabinfoItemData labinfoItemData,SysUser sysUser) {
        List<Map> itemList = new ArrayList<>();
        String sjys = sysUser.getNickName(); //获取当前登录用户的真实姓名,送检医生
        Long deptId = sysUser.getDeptId();
        Long sharedId = sysUser.getUserId(); //获取当前登录用户的id，被分享人
        if(deptId != null){
            labinfoItemData.setSjys(sjys);
            labinfoItemData.setDeptId(deptId);
            labinfoItemData.setSharedId(String.valueOf(sharedId));
            itemList = labinfoItemDataMapper.getItemListBySampleDecWay1(labinfoItemData);
        }
        return itemList;
    }

    @Override
    public List<LabinfoItemData> getItemListBySampleDecWay2(LabinfoItemData labinfoItemData, SysUser sysUser) {
        List<LabinfoItemData> itemList = new ArrayList<>();
        String sampleDecWay = labinfoItemData.getSampleDecWay();
        String sjys = sysUser.getNickName(); //获取当前登录用户的真实姓名,送检医生
        Long deptId = sysUser.getDeptId();
        Long sharedId = sysUser.getUserId(); //获取当前登录用户的id，被分享人
        String searchValue = labinfoItemData.getSearchValue();
        if(deptId != null){
            itemList = labinfoItemDataMapper.getItemListBySampleDecWay2(sampleDecWay,sjys,deptId,String.valueOf(sharedId),searchValue);
        }
        return itemList;
    }

    @Override
    public int shareItems(LabinfoItemData labinfoItemData) {
        if(labinfoItemData.getDeptId()!=null && labinfoItemData.getSharedId()!=null && labinfoItemData.getIds()!=null && labinfoItemData.getIds().length!=0){
            Long[] ids = labinfoItemData.getIds();
            for(int i = 0 ; i< ids.length ; i++){
                Long id = ids[i];
                //根据id获取item数据，如果已经被分享，则获取被分享人的id
                LabinfoItemData query = new LabinfoItemData();
                LabinfoItemData returnLabinfoItemData = labinfoItemDataMapper.selectLabinfoItemDataById(id);
                if(returnLabinfoItemData != null){
                    if(StringUtils.isNotEmpty(returnLabinfoItemData.getSharedId())){
                        String returnShareId = returnLabinfoItemData.getSharedId();
                        //判断当前传入的分享人id，是否已经在后台获取到的shareId里面,如果包含则跳过，否则保存
                        if(returnShareId.contains(labinfoItemData.getSharedId())){//包含
                            continue;
                        }else{
                            query.setSharedId(returnShareId + "," + labinfoItemData.getSharedId());
                        }
                    }else{
                        query.setSharedId(labinfoItemData.getSharedId());
                    }
                }
                query.setId(ids[i]);
                query.setIsShare("1");
                query.setDeptId(labinfoItemData.getDeptId());

                labinfoItemDataMapper.updateLabinfoItemData(query);
            }
            return labinfoItemData.getIds().length;
        }else{
            return 0;
        }

    }

    @Override
    public List<Map> getReceiveItemDateList(Map map) {
        String sjdwName = map.get("sjdwName")== null?"": map.get("sjdwName").toString();
        String patientPhone = map.get("patientPhone")== null?"": map.get("patientPhone").toString();
        return labinfoItemDataMapper.getReceiveItemDateList(sjdwName,patientPhone);
    }

    @Override
    public AjaxResult saveItem(List<LabinfoItemData> itemDataList) {
        String failureMsg = "";
        List<LabinfoItemData> errorList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(itemDataList)){
            try {
                itemDataList.stream().forEach(labinfoItemData -> {
                    String sampleSerialNumber = labinfoItemData.getSampleSerialNumber();
                    //根据outId查询id
                    if(StringUtils.isNotEmpty(sampleSerialNumber)){
                        Long id = labinfoItemDataMapper.selectIdBySampleSerialNumber(sampleSerialNumber);
                        if(id !=null){ // 存在则更新
                            labinfoItemData.setId(id);
                            labinfoItemData.setUpdateTime(new Date());
                            labinfoItemDataMapper.updateLabinfoItemData(labinfoItemData);
                        }else {
                            labinfoItemData.setId(null);
                            labinfoItemData.setSampleSerialNumber(sampleSerialNumber);
                            labinfoItemData.setCreateTime(new Date());
                            labinfoItemDataMapper.insertLabinfoItemData(labinfoItemData);
                        }
                    }else {
                        errorList.add(labinfoItemData);
                    }
                });
            }catch (Exception e){
                failureMsg = e.getMessage();
                log.error(e.getMessage());
                return AjaxResult.error(failureMsg);
            }
        }
        if(CollectionUtil.isNotEmpty(errorList)){
            return  AjaxResult.error(failureMsg,errorList);
        }
        return AjaxResult.success("item数据传输成功");
    }

    @Override
    public List<Map> getLabinfoItemDataList(LabinfoItemData labinfoItemData) {
        return labinfoItemDataMapper.getLabinfoItemDataList(labinfoItemData);
    }
}
